<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import orderAddrApi from '@/api/orderAddr_api.js'
import userApi from '@/api/user_api.js'
import seckillGoodsApi from '@/api/seckill/seckillGoods_api.js'
import goodsApi from '@/api/goods_api.js'

// 表格数据
const tableData = ref([])
const total = ref(0)
// 查询条件
const searchObj = ref({
  current: 1,
  limit: 10,
  id: '',
  user_id: '',
  seckill_goods_id: '',
  goods_id: '',
  address: '',
  username: '',
  seckill_goods_name: '',
  goods_name: ''
})

// 要修改或者新增的数据
const obj = ref({})

// 用户名到用户ID的映射
const userMap = ref({})

// 秒杀商品信息映射
const seckillGoodsMap = ref(new Map())

// 商品信息映射
const goodsMap = ref(new Map())

// 获取用户信息
const getUserInfo = async (userId) => {
  if (!userMap.value[userId]) {
    try {
      const userResult = await userApi.getUserById(userId)
      if (userResult && userResult.username) {
        userMap.value[userId] = userResult.username
      }
    } catch (error) {
      console.error(`获取用户${userId}信息失败:`, error)
    }
  }
  return userMap.value[userId]
}

// 获取秒杀商品信息
const getSeckillGoodsInfo = async (seckillGoodsId) => {
  if (!seckillGoodsMap.value.has(seckillGoodsId)) {
    try {
      const seckillGoodsResult = await seckillGoodsApi.getSeckillGoodsById(seckillGoodsId)
      if (seckillGoodsResult && seckillGoodsResult.data) {
        seckillGoodsMap.value.set(seckillGoodsId, seckillGoodsResult.data)
      } else if (seckillGoodsResult) {
        seckillGoodsMap.value.set(seckillGoodsId, seckillGoodsResult)
      }
    } catch (error) {
      console.error(`获取秒杀商品${seckillGoodsId}信息失败:`, error)
    }
  }
}

// 获取商品信息
const getGoodsInfo = async (goodsId) => {
  if (!goodsMap.value.has(goodsId)) {
    try {
      const goodsResult = await goodsApi.getGoodsById(goodsId)
      if (goodsResult && goodsResult.data) {
        goodsMap.value.set(goodsId, goodsResult.data)
      } else if (goodsResult) {
        goodsMap.value.set(goodsId, goodsResult)
      }
    } catch (error) {
      console.error(`获取商品${goodsId}信息失败:`, error)
    }
  }
}

// 根据秒杀商品ID获取商品名称
const getGoodsNameBySeckillGoodsId = (seckillGoodsId) => {
  if (!seckillGoodsId) return '';

  // 先从秒杀商品映射中获取秒杀商品信息
  const seckillGoodsInfo = seckillGoodsMap.value.get(seckillGoodsId);
  if (seckillGoodsInfo && seckillGoodsInfo.goods_id) {
    // 再从商品映射中获取商品名称
    const goodsInfo = goodsMap.value.get(seckillGoodsInfo.goods_id);
    if (goodsInfo && goodsInfo.name) {
      return goodsInfo.name;
    }
  }
  return '';
}

// 根据商品ID获取商品名称
const getGoodsNameByGoodsId = (goodsId) => {
  if (!goodsId) return '';

  const goodsInfo = goodsMap.value.get(goodsId);
  return goodsInfo && goodsInfo.name ? goodsInfo.name : '';
}

// 查询地址列表
const search = async () => {
  try {
    // 处理查询参数
    const queryParams = { ...searchObj.value };

    // 如果有用户名查询条件，先查询用户ID
    if (searchObj.value.username) {
      try {
        // 使用用户分页接口查找用户
        const userResult = await userApi.getUserPage(1, 100, { username: searchObj.value.username });
        if (userResult && userResult.records && userResult.records.length > 0) {
          // 找到匹配的用户，使用第一个匹配用户的ID进行查询
          queryParams.user_id = userResult.records[0].id;
        } else {
          // 没有找到匹配的用户，设置一个不可能存在的用户ID
          queryParams.user_id = -1;
        }
      } catch (error) {
        console.error('查询用户信息失败:', error);
        ElMessage.error("查询用户信息失败");
      }
    }

    // 如果有秒杀商品名查询条件，先通过商品名称查询商品ID，再通过商品ID查询秒杀商品ID
    if (searchObj.value.seckill_goods_name) {
      try {
        // 使用商品分页接口查找商品
        const goodsResult = await goodsApi.getGoodsPage(1, 100, { name: searchObj.value.seckill_goods_name });
        if (goodsResult && goodsResult.records && goodsResult.records.length > 0) {
          // 找到匹配的商品，使用第一个匹配的商品ID查询对应的秒杀商品
          const goodsId = goodsResult.records[0].id;
          console.log("goodsId:", goodsId);

          // 通过goods_id查找对应的秒杀商品
          const seckillGoodsResult = await seckillGoodsApi.getSeckillGoodsByGoodsId(goodsId);
          console.log("seckillGoodsResult:", seckillGoodsResult);
          if (seckillGoodsResult || seckillGoodsResult.data) {
            // 找到对应的秒杀商品ID
            queryParams.seckill_goods_id = seckillGoodsResult.id;
          } else if (seckillGoodsResult && Array.isArray(seckillGoodsResult) && seckillGoodsResult.length > 0) {
            // 如果返回的是数组，取第一个
            queryParams.seckill_goods_id = seckillGoodsResult[0].id;
          } else {
            // 没有找到对应的秒杀商品，设置一个不可能存在的秒杀商品ID
            queryParams.seckill_goods_id = -1;
          }
        } else {
          // 没有找到匹配的商品，设置一个不可能存在的秒杀商品ID
          queryParams.seckill_goods_id = -1;
        }
      } catch (error) {
        console.error('查询秒杀商品信息失败:', error);
        ElMessage.error("查询秒杀商品信息失败");
      }
    } else {
      // 如果没有秒杀商品名查询条件，确保seckill_goods_id为空字符串而不是默认值
      queryParams.seckill_goods_id = '';
    }

    // 如果有商品名查询条件，先查询商品ID
    if (searchObj.value.goods_name) {
      try {
        // 使用商品分页接口查找商品
        const goodsResult = await goodsApi.getGoodsPage(1, 100, { name: searchObj.value.goods_name });
        if (goodsResult && goodsResult.records && goodsResult.records.length > 0) {
          // 找到匹配的商品，使用第一个匹配的商品ID进行查询
          queryParams.goods_id = goodsResult.records[0].id;
        } else {
          // 没有找到匹配的商品，设置一个不可能存在的商品ID
          queryParams.goods_id = -1;
        }
      } catch (error) {
        console.error('查询商品信息失败:', error);
        ElMessage.error("查询商品信息失败");
      }
    } else {
      // 如果没有商品名查询条件，确保goods_id为空字符串
      queryParams.goods_id = '';
    }

    // 删除名称查询参数，只传递ID参数给后端
    delete queryParams.username;
    delete queryParams.seckill_goods_name;
    delete queryParams.goods_name;

    console.log('发送的查询参数:', queryParams)
    const result = await orderAddrApi.getOrderAddrPage(queryParams.current, queryParams.limit, queryParams);
    console.log('收到的响应数据:', result)

    // 处理地址数据，获取关联信息
    if (result.records) {
      // 先获取所有关联的ID
      const seckillGoodsIds = [];
      const goodsIds = [];

      for (let i = 0; i < result.records.length; i++) {
        const addr = result.records[i];

        // 收集秒杀商品ID
        if (addr.seckill_goods_id) {
          seckillGoodsIds.push(addr.seckill_goods_id);
        }

        // 收集商品ID
        if (addr.goods_id) {
          goodsIds.push(addr.goods_id);
        }

        // 获取用户名
        if (addr.user_id && !userMap.value[addr.user_id]) {
          await getUserInfo(addr.user_id)
        }
        addr.username = userMap.value[addr.user_id] || addr.user_id;
      }

      // 批量获取秒杀商品信息
      for (const seckillGoodsId of seckillGoodsIds) {
        await getSeckillGoodsInfo(seckillGoodsId);

        // 同时获取对应的商品信息
        const seckillGoodsInfo = seckillGoodsMap.value.get(seckillGoodsId);
        if (seckillGoodsInfo && seckillGoodsInfo.goods_id) {
          await getGoodsInfo(seckillGoodsInfo.goods_id);
        }
      }

      // 批量获取商品信息
      for (const goodsId of goodsIds) {
        await getGoodsInfo(goodsId);
      }
    }

    tableData.value = result.records
    total.value = result.total
  } catch (error) {
    console.error('查询订单地址列表时出错:', error)
    tableData.value = []
    total.value = 0
  }
}

// 页面加载完成后查询数据
onMounted(() => {
  search()
})

// 重置查询条件
const resetSearch = () => {
  searchObj.value.id = ''
  searchObj.value.user_id = ''
  searchObj.value.seckill_goods_id = ''
  searchObj.value.goods_id = ''
  searchObj.value.address = ''
  searchObj.value.username = ''
  searchObj.value.seckill_goods_name = ''
  searchObj.value.goods_name = ''
  searchObj.value.current = 1
  search()
}

// 分页大小改变
const handleSizeChange = () => {
  search()
}

// 当前页改变
const handleCurrentChange = () => {
  search()
}

// 处理查询
const handlerSearch = () => {
  searchObj.value.current = 1
  search()
}

// 定义对话框的显示状态
const editWinVisible = ref(false)
const addWinVisible = ref(false)

// 处理编辑
const handleEdit = (index, row) => {
  obj.value = {...row}
  editWinVisible.value = true
}

// 处理删除
const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      '确认删除该行数据吗?',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(async () => {
        await orderAddrApi.deleteOrderAddr(row.id)
        // 重新加载数据
        searchObj.value.current = 1
        await search()
      })
      .catch(() => {
      })
}

// 编辑对话框的取消按钮点击事件
const editCancel = () => {
  obj.value = {}
  editWinVisible.value = false
}

// 编辑对话框的提交按钮点击事件
const editCommit = async () => {
  try {
    await orderAddrApi.updateOrderAddr(obj.value)
    await search()
    editWinVisible.value = false
    ElMessage.success('更新成功')
  } catch (error) {
    ElMessage.error('更新失败: ' + error.message)
  }
}

/*// 处理添加
const handlerAdd = () => {
  obj.value = {}
  addWinVisible.value = true
}*/

/*// 新增对话框的取消按钮点击事件
const addCancel = () => {
  obj.value = {}
  addWinVisible.value = false
}*/

/*
// 新增对话框的提交按钮点击事件
const addCommit = async () => {
  try {
    await orderAddrApi.addOrderAddr(obj.value)
    await search()
    addWinVisible.value = false
    ElMessage.success('添加成功')
  } catch (error) {
    ElMessage.error('添加失败: ' + error.message)
  }
}
*/

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  return dateTimeStr.replace('T', ' ')
}
</script>

<template>
  <div class="order-addr-management">
    <h2>订单地址管理</h2>

    <div class="tips-container">
      <el-alert
          title="请输入完整的名称，否则会查询不到"
          type="info"
          show-icon
          size="small"
          class="search-tip"
          :closable="false"
      />
    </div>

    <!-- 查询条件 -->
    <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top:10px">
      <!--      <el-form-item label="地址ID">-->
      <!--        <el-input v-model="searchObj.id" placeholder="请输入地址ID" clearable/>-->
      <!--      </el-form-item>-->
      <el-form-item label="用户名">
        <el-input v-model="searchObj.username" placeholder="请输入用户名" clearable/>
      </el-form-item>
      <el-form-item label="秒杀商品名">
        <el-input v-model="searchObj.seckill_goods_name" placeholder="请输入秒杀商品名" clearable/>
      </el-form-item>
      <el-form-item label="商品名">
        <el-input v-model="searchObj.goods_name" placeholder="请输入商品名" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handlerSearch">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="resetSearch">重置</el-button>
      </el-form-item>
      <!--      <el-form-item>
              <el-button type="primary" @click="handlerAdd">新增</el-button>
            </el-form-item>-->
    </el-form>

    <!-- 地址表格 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="地址ID" width="80"></el-table-column>
      <el-table-column prop="username" label="用户名" width="120">
        <template #default="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column prop="seckill_goods_id" label="秒杀商品" width="150">
        <template #default="scope">
          <span v-if="scope.row.seckill_goods_id">
            {{ getGoodsNameBySeckillGoodsId(scope.row.seckill_goods_id) }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="goods_id" label="商品" width="150">
        <template #default="scope">
          <span v-if="scope.row.goods_id">
            {{ getGoodsNameByGoodsId(scope.row.goods_id) }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="详细地址"></el-table-column>
      <el-table-column label="处理按钮" width="150">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        :page-sizes="[10, 20, 50, 100]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 编辑对话框 -->
    <el-dialog v-model="editWinVisible" title="编辑订单地址" width="500">
      <el-form :model="obj">
        <el-form-item label="用户ID" :label-width="120">
          <el-input v-model.number="obj.user_id" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="秒杀商品ID" :label-width="120">
          <el-input v-model.number="obj.seckill_goods_id" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="商品ID" :label-width="120">
          <el-input v-model.number="obj.goods_id" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="详细地址" :label-width="120">
          <el-input v-model="obj.address" type="textarea" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="是否删除" :label-width="120">
          <el-radio-group v-model="obj.is_del">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">已删除</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editCancel">取消</el-button>
          <el-button type="primary" @click="editCommit">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增对话框 -->
    <el-dialog v-model="addWinVisible" title="新增订单地址" width="500">
      <el-form :model="obj">
        <el-form-item label="用户ID" :label-width="120">
          <el-input v-model.number="obj.user_id" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="秒杀商品ID" :label-width="120">
          <el-input v-model.number="obj.seckill_goods_id" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="商品ID" :label-width="120">
          <el-input v-model.number="obj.goods_id" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="详细地址" :label-width="120">
          <el-input v-model="obj.address" type="textarea" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addCancel">取消</el-button>
          <el-button type="primary" @click="addCommit">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.order-addr-management {
  padding: 20px;
  background-color: #fff;
}

.order-addr-management h2 {
  margin-bottom: 20px;
}

.demo-form-inline {
  margin-bottom: 20px;
}

.tips-container {
  margin-bottom: 15px;
}

</style>
